import React, { useState } from 'react';
import { parseRecipe, createRecipe } from '../services/api';
import ImageUploader from './ImageUploader';

const ChatWindow = ({ onRecipeSaved }) => {
  const [text, setText] = useState('');
  const [parsedData, setParsedData] = useState(null);
  const [uploadedImages, setUploadedImages] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');

  const handleParse = async () => {
    if (!text.trim()) return;
    setIsLoading(true);
    setError('');
    setParsedData(null);
    setUploadedImages([]);
    try {
      const response = await parseRecipe(text);
      setParsedData(response.data);
    } catch (err) {
      setError('解析食谱失败。请检查后端连接。');
      console.error(err);
    } finally {
      setIsLoading(false);
    }
  };

  const handleSave = async () => {
    if (!parsedData) return;
    setIsLoading(true);
    setError('');
    try {
      const recipeToSave = {
        ...parsedData,
        image_urls: uploadedImages,
      };
      await createRecipe(recipeToSave);
      onRecipeSaved(); // Notify parent component to refresh the list
      setText('');
      setParsedData(null);
      setUploadedImages([]);
    } catch (err) {
      setError('保存食谱失败。');
      console.error(err);
    } finally {
      setIsLoading(false);
    }
  };

  const handleUploadSuccess = (imageUrl) => {
    setUploadedImages(prevImages => [...prevImages, imageUrl]);
  };

  return (
    <div className="card">
      <h2>记录新食谱</h2>
      <textarea
        className="form-control"
        value={text}
        onChange={(e) => setText(e.target.value)}
        placeholder="描述您制作的菜肴，例如：'今天我做了意大利肉酱面...'"
        rows="5"
      />
      <div style={{ marginTop: '10px', display: 'flex', gap: '10px' }}>
        <button onClick={handleParse} disabled={isLoading} className="btn btn-primary">
          {isLoading ? '正在解析...' : '解析食谱'}
        </button>
        <button onClick={handleSave} disabled={!parsedData || isLoading} className="btn btn-success">
          {isLoading ? '正在保存...' : '保存食谱'}
        </button>
      </div>

      {error && <p style={{ color: 'var(--danger-color)', marginTop: '10px' }}>{error}</p>}

      {parsedData && (
        <div className="card" style={{ marginTop: '20px' }}>
          <h3>解析结果:</h3>
          <h4>{parsedData.dish_name}</h4>
          <p><strong>配料:</strong> {parsedData.ingredients.join(', ')}</p>
          <p><strong>烹饪方法:</strong></p>
          <ol>{parsedData.method.map((step, i) => <li key={i}>{step}</li>)}</ol>
          {parsedData.comment && <p><strong>评论:</strong> {parsedData.comment}</p>}
          {parsedData.self_critique && <p><strong>自我评价:</strong> {parsedData.self_critique}</p>}
          
          <ImageUploader onUploadSuccess={handleUploadSuccess} />

          {uploadedImages.length > 0 && (
            <div className="image-gallery" style={{ marginTop: '10px' }}>
              {uploadedImages.map((url, index) => (
                <img key={index} src={url} alt={`upload-preview-${index}`} className="image-preview" />
              ))}
            </div>
          )}
        </div>
      )}
    </div>
  );
};

export default ChatWindow;
